from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import session

from info import constants, db
from info.models import Category, News
from info.utils.common import user_login_data
from info.utils.image_sstorage import storage
from info.utils.response_code import RET
from . import profile_blu


@profile_blu.route('/info')
@user_login_data
def user_info():
    """
    个人中心页面渲染视图
    :return: 个人中心页面
    """
    user = g.user
    if not user:
        return redirect('/')

    data = {
        'user_info': user.to_dict()
    }

    return render_template('news/user.html', data=data)


@profile_blu.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():
    """
    个人基本资料视图
    :return: 基本资料页面/修改状态
    """
    user = g.user

    # GET请求为显示页面,POST为数据提交
    if request.method == 'GET':
        data = {
            'user_info': user.to_dict()
        }
        return render_template('news/user_base_info.html', data=data)

    # -------------------------不同功能分割线-----------------------------------

    # 获取参数
    nick_name = request.json.get('nick_name')  # 用户名
    signature = request.json.get('signature')  # 个性签名
    gender = request.json.get('gender')  # 性别, MAN为男 WOMEN为女

    # 判断参数
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.DATAERR, errmsg="参数错误")

    if gender not in ['MAN', 'WOMEN']:
        return jsonify(errno=RET.DATAERR, errmsg="参数错误")

    # 数据修改保存
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender

    # 更新session数据
    session['nick_name'] = nick_name

    return jsonify(errno=RET.OK, errmsg="操作成功")


@profile_blu.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():
    """
    修改头像视图
    :return: 渲染页面/修改状态
    """
    user = g.user

    # GET请求为渲染页面
    if request.method == 'GET':

        data = {
            'user_info': user.to_dict()
        }
        return render_template('news/user_pic_info.html', data=data)

    # --------------------不同功能分割线----------------------------------

    try:
        # 获取参数,读取文件
        avatar_file = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="数据读取失败")

    # 判断数据
    if not avatar_file:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        # 将文件上传到七牛云
        url = storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传文件失败")

    # 更新用户头像
    user.avatar_url = url

    # 手动提交,应为数据在返回时就要用到,而自动提交时在返回会再提交的
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="提交错误")

    data = {
        'avatar_url': constants.QINIU_DOMIN_PREFIX + url
    }

    return jsonify(errno=RET.OK, errmsg="操作成功", data=data)


@profile_blu.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def pass_info():
    """
    修改密码视图
    :return: 修改密码页面渲染/操作状态
    """
    user = g.user

    if request.method == 'GET':
        return render_template('news/user_pass_info.html')

        # --------------------不同功能分割线----------------------------------

    # 获取参数
    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')

    # 判断参数
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 判断输入的旧密码是否相同
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原密码错误")

    user.password = new_password

    return jsonify(errno=RET.OK, errmsg="密码修成功")


@profile_blu.route('/collection')
@user_login_data
def collection():
    """
    用户新闻收藏显示视图
    :return: 收藏页面
    """
    user = g.user
    # 获得参数
    p = request.args.get('p', 1)

    # 判断参数
    if not p:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询数据
    collections = list()  # 保存查询显示数据
    current_page = 1  # 当前页数
    total_page = 1  # 总页数
    try:

        paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        collections = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")

    # 获得循环列表
    collections_list = list()
    for news in collections:
        collections_list.append(news.to_basic_dict())

    data = {
        'collections': collections_list,
        'current_page': current_page,
        'total_page': total_page
    }

    return render_template('news/user_collection.html', data=data)


@profile_blu.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():
    """
    发布新闻视图
    :return: 发布页面/新闻列表页面
    """
    # 请求方式为GET时为渲染页面
    if request.method == 'GET':
        categories = list()
        try:
            # 查询所以分类
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="查询错误")

        categories_list = list()  # 存储分类列表
        for category in categories:
            categories_list.append(category.to_dict())

        # 删除 最新分类
        categories_list.pop(0)

        data = {
            'categories': categories_list
        }

        return render_template('news/user_news_release.html', data=data)

    # -----------------------------不同功能分割线------------------------

    # 获得参数
    title = request.form.get("title")
    source = "个人发布"
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")
    # 1.1 判断数据是否有值
    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    try:
        # 获取图片
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="读取图片失败")

    try:
        # 将图片上传到七牛云
        url = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="七牛云上传图片失败")

    # 初始化新闻模型,数据写入
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + url
    news.category_id = category_id
    news.user_id = g.user.id

    news.status = 1  # 审核状态属性, 1 代表待审核

    db.session.add(news)

    return jsonify(errno=RET.OK, errmsg="操作成功")


@profile_blu.route('/news_list')
@user_login_data
def news_list():
    """
    用户发布新闻列表视图
    :return: 列表页面
    """
    user = g.user

    # 获得参数
    p = request.args.get('p', 1)

    # 判断参数
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    news_li = list()
    current_page = 1
    total_page = 1
    try:
        # 查询数据
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.HOME_PAGE_MAX_NEWS, False)
        news_li = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")

    news_dict_li = list()
    for i in news_li:
        news_dict_li.append(i.to_review_dict())

    data = {
        'news_list': news_dict_li,
        'current_page': current_page,
        'total_page': total_page
    }

    return render_template('news/user_news_list.html', data=data)


@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    """
    个人中心关注视图
    :return:
    """
    # 获取页数参数
    p = request.args.get("p", 1)
    # 判断参数
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user

    follows = []
    current_page = 1
    total_page = 1
    try:
        # 查询数据
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        # 获取当前页数据
        follows = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())

    data = {
        "users": user_dict_li,
        "total_page": total_page,
        "current_page": current_page

    }
    return render_template('news/user_follow.html', data=data)